#coding:utf-8
'''
这里添加模块注释，注释也要注意缩进
'''


from urllib import request   #导入模块urllib，用于发起网络请求，获取数据
import re                    #导入模块re，用于实现正则提取信息


class Spider():
    '''
    这里是类注释
    '''
    #需要抓取的网络链接
    url = "https://www.panda.tv/cate/kingglory"

    #正则：获取显示视频信息的div代码串
    reString_div = '<div class="video-info">([\s\S]*?)</div>'   
    #正则：获取主播名
    reString_name = '</i>([\s\S]*?)</span>'
    #正则：获取视频浏览量
    reString_number = '<span class="video-number">([\s\S]*?)</span>'


    def __fetch_content(self):
        '''
        这里是方法注释
        请求网络，获取整个网页的Hmtl字符串
        '''
        r = request.urlopen(Spider.url)
        data = r.read()
        htmlString = str(data,encoding="utf-8")
        return htmlString


    def __alalysis(self,htmlString):
        '''
        使用正则初步获取数据，得到主播信息(主播名和浏览量)的数组
        '''
        videoInfos = re.findall(Spider.reString_div,htmlString)
        anchors = []
        #print(videoInfos[0])
        for html in videoInfos :
            name = re.findall(Spider.reString_name,html)
            number = re.findall(Spider.reString_number,html)
            anchor = {"name":name,"number":number}
            anchors.append(anchor)
        #print(anchors[0])
        return anchors


    def __refine(self,anchors):
        '''
        将数据进一步提炼，去除空格等多余字符
        '''
        f = lambda anchor :{"name":anchor["name"][0].strip(),"number":anchor["number"][0]}
        newAnchors = list(map(f,anchors))
        #print(newAnchors)
        return newAnchors


    def __sort(self,anchors):
        '''
        数据分析：排序浏览量从大到小 
        '''
        anchors = sorted(anchors,key=self.__sort_seed,reverse = True)
        return anchors


    def __sort_seed(self,anchor):
        '''
        排序规则
        '''
        list_nums = re.findall('\d*',anchor["number"])
        number = float(list_nums[0])
        if '万' in anchor["number"]:
            number = number * 10000
        return number


    def __show(self,anchors):
        '''
        展示数据，将已经排序好的数据打印出来
        '''
        for rank in range(0,len(anchors)):
            print("第" + str(rank+1) +"名：" + anchors[rank]["number"] + "\t"  + anchors[rank]["name"])


    def startRun(self):
       '''
       程序入口，开始运行爬虫
       '''
       htmlString = self.__fetch_content()
       anchors = self.__alalysis(htmlString)
       anchors = self.__refine(anchors)
       anchors  = self.__sort(anchors)
       self.__show(anchors)


spider = Spider()
spider.startRun()
